package com.gz;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class sender {
    public static void main(String[] args) throws IOException {
        //这里我是在一台电脑上操作发送和接受的，端口要不一样
        //如果在不同电脑上端口号可以一样
        DatagramSocket datagramSocket = new DatagramSocket(9998);

        //发送
        byte[] buf = "你好接收端，今天吃火锅".getBytes();
        DatagramPacket datagramPacket =
                new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.119.1"), 9999);
        datagramSocket.send(datagramPacket);
        //接受接收端回复
        buf=new byte[1024];
        datagramPacket=new DatagramPacket(buf, buf.length);
        datagramSocket.receive(datagramPacket);//等待接收reserver端口发送的数据，若未收到，阻塞等待

        int length = datagramPacket.getLength();
        String str = new String(datagramPacket.getData(), 0, length);

        System.out.println(str);


        datagramSocket.close();
        System.out.println("sender端结束");

    }
}
